﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using Newtonsoft.Json;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using WebSocketChat.Common.Database;
using WebSocketChat.Common;
using System.Configuration;
using WebSocketChat.Common.Client;

namespace WebSocketChat.Client
{
    public partial class LoginForm : CCSkinMain
    {
        public LoginForm()
        {
            InitializeComponent();
        }
        private void LoginForm_Load(object sender, EventArgs e)
        {

        }
        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                var ip = ConfigurationManager.AppSettings["ServerIP"];
                //http://localhost/WebSocketChat.Web/Chat/SignIn
                var res = HttpHelper.PostDataGetHtml("http://" + ip + "/WebSocketChat.Web/api/Login", "{LoginID:\"" + tbUsername.Text + "\",PassWords:\"" + EncryptHelper.EncryptMD5(tbPassword.Text.Trim()) + "\"}");
                var jsonResult = JsonConvert.DeserializeObject<ResultObject<ChatUser>>(res);

                if (jsonResult.code == 200)
                {
                    ClientSocket client = new ClientSocket(jsonResult.data);
                    client.Connect(ip, 11011, 1000);

                    //发送在线
                    IMessage msg = new CommandMessage()
                    {
                        Data = jsonResult.data,
                        Sender = jsonResult.data.ID,
                        Type = MessageType.Online
                    };
                    client.Send(msg);

                    //显示好友列表
                    MainWindow mw = new MainWindow(client);
                    this.Hide();
                    mw.Show();
                }
                else
                {
                    MessageBoxEx.Show(jsonResult.msg);
                }
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(ex.Message);
            }
        }

    }

    public class ResultObject<T> where T : class
    {
        public int code { get; set; }
        public string msg { get; set; }
        public int count { get; set; }
        public T data { get; set; }
    }
}
